/**
 * Copyright &copy; 2013-2016 山东易科德软件有限公司   All rights reserved.
 */
package cn.net.ecode.mdm.web;

import cn.net.ecode.common.config.Global;
import cn.net.ecode.common.persistence.Page;
import cn.net.ecode.common.utils.IdGen;
import cn.net.ecode.common.utils.StringUtils;
import cn.net.ecode.common.utils.excel.ExportExcel;
import cn.net.ecode.common.utils.excel.ImportExcel;
import cn.net.ecode.common.web.BaseController;
import cn.net.ecode.constant.YesOrNoEnum;
import cn.net.ecode.elec.api.service.ElecUserService;
import cn.net.ecode.exception.TPException;
import cn.net.ecode.mdm.entity.MdmBtypeInfo;
import cn.net.ecode.mdm.service.MdmBtypeInfoService;
import cn.net.ecode.modules.sys.entity.User;
import cn.net.ecode.modules.sys.service.UserService;
import cn.net.ecode.modules.sys.utils.DictUtils;
import com.google.common.collect.Lists;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 企业Controller
 *
 * @author xiaodunshan
 * @version 2019-08-26
 */
@Controller
@RequestMapping(value = "${adminPath}/mdm/mdmBtypeInfo")
public class MdmBtypeInfoController extends BaseController {

    @Autowired
    private MdmBtypeInfoService mdmBtypeInfoService;

    @Autowired
    private UserService userService;

    @Autowired
    private ElecUserService elecUserService;

    /**
     * 获取数据
     */
    @ModelAttribute
    public MdmBtypeInfo get(String id, boolean isNewRecord) {
        return mdmBtypeInfoService.get(id, isNewRecord);
    }

    /**
     * 查询列表
     */
    @RequiresPermissions("mdm:mdmBtypeInfo:view")
    @RequestMapping(value = {"list", ""})
    public String list(MdmBtypeInfo mdmBtypeInfo, Model model) {
        model.addAttribute("mdmBtypeInfo", mdmBtypeInfo);
        return "ecode/mdm/mdmBtypeInfoList";
    }

    /**
     * 查询列表数据
     */
    @RequiresPermissions("mdm:mdmBtypeInfo:view")
    @ResponseBody
    @RequestMapping(value = "listData")
    public Page<MdmBtypeInfo> listData(MdmBtypeInfo mdmBtypeInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<MdmBtypeInfo> page = mdmBtypeInfoService.findPage(new Page<MdmBtypeInfo>(request, response), mdmBtypeInfo);
        return page;
    }

    /**
     * 查看编辑表单
     */
    @RequiresPermissions("mdm:mdmBtypeInfo:view")
    @RequestMapping(value = "form")
    public String form(MdmBtypeInfo mdmBtypeInfo, Model model) {
        model.addAttribute("mdmBtypeInfo", mdmBtypeInfo);
        return "ecode/mdm/mdmBtypeInfoForm";
    }

    /**
     * 保存数据
     */
    @RequiresPermissions("mdm:mdmBtypeInfo:edit")
    @ResponseBody
    @RequestMapping(value = "save")
    public String save(MdmBtypeInfo mdmBtypeInfo) {
        StringBuilder message = new StringBuilder();
        if (!beanValidator(message, mdmBtypeInfo)) {
            return renderResult(Global.FALSE, message);
        }
        mdmBtypeInfoService.save(mdmBtypeInfo);
        return renderResult(Global.TRUE, "保存企业成功！");
    }

    /**
     * 删除数据
     */
    @RequiresPermissions("mdm:mdmBtypeInfo:edit")
    @ResponseBody
    @RequestMapping(value = "delete")
    public String delete(MdmBtypeInfo mdmBtypeInfo) {
        mdmBtypeInfoService.delete(mdmBtypeInfo);
        return renderResult(Global.TRUE, "删除企业成功！");
    }


    @RequestMapping(value = "select")
    public String select(MdmBtypeInfo mdmBtypeInfo, Model model) {
        model.addAttribute("mdmBtypeInfo", mdmBtypeInfo);
        return "ecode/mdm/btypeSelect";
    }

    @RequiresPermissions("mdm:mdmBtypeInfo:edit")
    @ResponseBody
    @RequestMapping(value = "audit")
    public String audit(MdmBtypeInfo mdmBtypeInfo) {
        // 变更企业信息
        mdmBtypeInfo.setAuditStatus(String.valueOf(YesOrNoEnum.YES.getCode()));
        mdmBtypeInfo.setIsNewRecord(false);
        mdmBtypeInfoService.save(mdmBtypeInfo);

        // 变更管理员信息
        User user = new User();
        user.setLoginCode(mdmBtypeInfo.getLinkmanTel());
        User admin = userService.getByLoginCode(user);
        if (admin == null) {
            return renderResult(Global.FALSE, "联系人手机号无法查到对应的管理员，无法通过审核，请先生成管理员账号！");
        }
        admin.setExtendS3(String.valueOf(YesOrNoEnum.YES.getCode()));
        admin.setIsNewRecord(false);
        userService.save(admin);

        return renderResult(Global.TRUE, "审核企业成功！");
    }

    @RequiresPermissions("mdm:mdmBtypeInfo:edit")
    @ResponseBody
    @RequestMapping(value = "generateAdminAccount")
    public String generateAdminAccount(MdmBtypeInfo mdmBtypeInfo) {
        User user = new User();
        user.setLoginCode(mdmBtypeInfo.getLinkmanTel());
        User admin = userService.getByLoginCode(user);
        if (admin != null) {
            return renderResult(Global.FALSE, "该企业已经生成管理员账号，无需重复生成");
        }
        elecUserService.registerAdminNoMdm(mdmBtypeInfo);

        return renderResult(Global.TRUE, "管理员账号生成成功！");
    }

    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "导入模板.xlsx";
            List<MdmBtypeInfo> list = Lists.newArrayList();
            new ExportExcel("企业数据模板", MdmBtypeInfo.class, 2).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + adminPath + "/mdm/mdmBtypeInfo/list?repage";
    }

    @RequestMapping(value = "import", method = RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
        try {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<MdmBtypeInfo> list = ei.getDataList(MdmBtypeInfo.class);
            for (MdmBtypeInfo mdmBtypeInfo : list) {
                try {
                    String btypeClass = DictUtils.getDictValue(mdmBtypeInfo.getClassifyName(), "btype_classify", "");
                    String btypeType = DictUtils.getDictValue(mdmBtypeInfo.getTypeName(), "btype_type", "");
                    String btypeArea = DictUtils.getDictValue(mdmBtypeInfo.getAreaName(), "btype_area", "");
                    String btypeScale = DictUtils.getDictValue(mdmBtypeInfo.getScaleName(), "btype_scale", "");
                    if (StringUtils.isBlank(btypeClass)) {
                        mdmBtypeInfo.setClassifyName(null);
                        mdmBtypeInfo.setClassifyCode(null);
                    } else {
                        mdmBtypeInfo.setClassifyCode(btypeClass);
                    }
                    if (StringUtils.isBlank(btypeType)) {
                        mdmBtypeInfo.setTypeCode(null);
                        mdmBtypeInfo.setTypeName(null);
                    } else {
                        mdmBtypeInfo.setTypeCode(btypeType);
                    }
                    if (StringUtils.isBlank(btypeArea)) {
                        mdmBtypeInfo.setAreaCode(null);
                        mdmBtypeInfo.setAreaName(null);
                    } else {
                        mdmBtypeInfo.setAreaCode(btypeArea);
                    }
                    if (StringUtils.isBlank(btypeScale)) {
                        mdmBtypeInfo.setScaleCode(null);
                        mdmBtypeInfo.setScaleName(null);
                    } else {
                        mdmBtypeInfo.setScaleCode(btypeScale);
                    }
                    mdmBtypeInfo.setPassword("123456");
                    mdmBtypeInfo.setValidatePassword("123456");

                    if (StringUtils.isNotBlank(mdmBtypeInfo.getLinkmanTel())) {
                        elecUserService.registerAdmin(mdmBtypeInfo);
                    } else {
                        // 保存企业信息
                        mdmBtypeInfo.setIsNewRecord(true);
                        mdmBtypeInfo.setId(IdGen.nextId());
                        mdmBtypeInfoService.save(mdmBtypeInfo);
                    }
                    successNum++;
                } catch (Exception ex) {
                    failureMsg.append("<br/>导入失败：" + ex.getMessage());
                    System.out.println("导入结算数据失败！失败信息：" + ex.getMessage());

                    failureNum++;
                }
            }
            if (failureNum > 0) {
                failureMsg.insert(0, "，失败 " + failureNum + " 条结算数据信息，导入信息如下：");
                addMessage(redirectAttributes, "已成功导入 " + successNum + " 条结算数据信息" + failureMsg + "<br/>");
            } else {
                addMessage(redirectAttributes, "已成功导入 " + successNum + " 条结算数据信息" + failureMsg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            addMessage(redirectAttributes, "导入结算数据失败！失败信息：" + e.getMessage());
            System.out.println("导入结算数据失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + adminPath + "/mdm/mdmBtypeInfo/list?repage";
    }
}